package com.oss.service.oss;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oss.dto.oss.DeleteByIdDto;
import com.oss.dto.oss.investmentadvice.AddDto;
import com.oss.dto.oss.investmentadvice.PageDto;
import com.oss.dto.oss.investmentadvice.UpdateDto;
import com.oss.dto.oss.investmentadvice.WebQueryDto;
import com.oss.entity.oss.CapitalManage;
import com.oss.entity.oss.InvestmentAdvice;
import com.oss.entity.oss.InvestmentAdviceDetail;
import com.oss.entity.oss.Student;
import com.oss.enums.IsDeletedEnum;
import com.oss.mapper.oss.InvestmentAdviceMapper;
import com.oss.service.system.UserService;
import com.oss.util.SnowFlakeUtil;
import com.oss.vo.oss.investmentadvice.InvestmentAdviceDetailVO;
import com.oss.vo.oss.investmentadvice.InvestmentAdviceVO;
import com.oss.vo.oss.investmentadvice.WebInvestmentAdviceVO;
import com.oss.vo.oss.student.StudentVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chengqiang
 */
@Service
public class InvestmentAdviceService extends ServiceImpl<InvestmentAdviceMapper, InvestmentAdvice> {
    @Autowired
    UserService userService;
    @Autowired
    StudentService studentService;
    @Autowired
    HttpServletRequest request;
    @Autowired
    InvestmentAdviceDetailService investmentAdviceDetailService;
    public List<WebInvestmentAdviceVO> getWebList(WebQueryDto dto) {
        List<WebInvestmentAdviceVO> returnList = new ArrayList<>();
        String studentID = request.getHeader("oss-studentID");
        // 查询2天内的
        List<InvestmentAdviceDetail> detailList = investmentAdviceDetailService.selectByStudentID(studentID);
        if (CollectionUtils.isNotEmpty(detailList)) {
            Set<String> mids = detailList.stream().map(InvestmentAdviceDetail::getMid).collect(Collectors.toSet());
            LambdaQueryWrapper<InvestmentAdvice> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(InvestmentAdvice::getIsDeleted, IsDeletedEnum.NO.getFlag());
            wrapper.in(InvestmentAdvice::getId, mids);
            wrapper.eq(StringUtils.isNotBlank(dto.getInstrumentCode()),InvestmentAdvice::getInstrumentCode,dto.getInstrumentCode());
            List<InvestmentAdvice> list = this.list(wrapper);
            returnList =  list.stream().map(entity->{
                WebInvestmentAdviceVO vo = new WebInvestmentAdviceVO();
                BeanUtils.copyProperties(entity,vo);
                InvestmentAdviceDetail detail = detailList.stream().filter(item->item.getMid().equals(entity.getId())).findFirst().get();
                vo.setStatus(detail.getStatus());
                return vo;
            }).collect(Collectors.toList());
        }
        return returnList;
    }
    public IPage<InvestmentAdviceVO> selectByPage(PageDto dto) {
        LambdaQueryWrapper<InvestmentAdvice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(InvestmentAdvice::getIsDeleted, IsDeletedEnum.NO.getFlag());
        wrapper.eq(StringUtils.isNotBlank(dto.getInstrumentCode()),InvestmentAdvice::getInstrumentCode,dto.getInstrumentCode());
        String originHeader = request.getHeader("oss-origin");
        // 如果来源是网页端 , 校验用户角色 , 如果角色是admin,则查询所有, 否则校验学员ID不能为空, 且只能查询对应学员的数据
        if ("1".equals(originHeader)) {
            String roleHeader = request.getHeader("oss-role");
            if (StringUtils.isNotBlank(roleHeader) && roleHeader.contains("admin")) {

            } else {
                String studentID = request.getHeader("oss-studentID");
                wrapper.eq(InvestmentAdvice::getCreatorId,studentID);
            }
        }
        IPage<InvestmentAdvice> page = this.page(new Page<>(dto.getPageNo(), dto.getPageSize()), wrapper);
        Map<String,String> userMap = new HashMap<>();
        Map<String, List<InvestmentAdviceDetailVO>> detailMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(page.getRecords())) {
            // 获取创建人和修改人ID
            Set<String> userIds = page.getRecords().stream().map(InvestmentAdvice::getCreatorId).collect(Collectors.toSet());
            userIds.addAll(page.getRecords().stream().map(InvestmentAdvice::getUpdatorId).collect(Collectors.toSet()));
            userMap = userService.selectByIds(userIds);
            Set<String> ids = page.getRecords().stream().map(InvestmentAdvice::getId).collect(Collectors.toSet());
            detailMap = investmentAdviceDetailService.getByMID(ids);
        }
        Map<String, String> finalUserMap = userMap;
        Map<String, List<InvestmentAdviceDetailVO>> finalDetailMap = detailMap;
        return page.convert(entity->{
            InvestmentAdviceVO vo = new InvestmentAdviceVO();
            BeanUtils.copyProperties(entity,vo);
            vo.setDetailList(finalDetailMap.get(entity.getId()));
            vo.setCreatorName(finalUserMap.get(entity.getCreatorId()));
            vo.setUpdatorName(finalUserMap.get(entity.getUpdatorId()));
            return vo;
        });
    }

    public String add(AddDto dto) {
        InvestmentAdvice entity = new InvestmentAdvice();
        BeanUtils.copyProperties(dto,entity);
        entity.setId(SnowFlakeUtil.getID());
        investmentAdviceDetailService.add(entity.getId(),dto.getStudentIDSet());
        this.save(entity);
        return "操作成功";
    }

    public String approval(UpdateDto dto) {
        investmentAdviceDetailService.approval(dto);
        return "操作成功";
    }

    public String delete(DeleteByIdDto dto) {
        LambdaUpdateWrapper<InvestmentAdvice> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(InvestmentAdvice::getId,dto.getId());
        lambdaUpdateWrapper.set(InvestmentAdvice::getIsDeleted,IsDeletedEnum.YES.getFlag());
        this.update(null,lambdaUpdateWrapper);
        return "操作成功";
    }

    public InvestmentAdviceVO getByID(String id) {
        InvestmentAdviceVO vo = new InvestmentAdviceVO();
        InvestmentAdvice entity = this.getById(id);
        BeanUtils.copyProperties(entity,vo);
        Set<String> ids = new HashSet<>();
        ids.add(id);
        Map<String, List<InvestmentAdviceDetailVO>> detailMap = investmentAdviceDetailService.getByMID(ids);
        vo.setDetailList(detailMap.get(id));
        return vo;
    }
}
